import React, {Component} from 'react'
import {Input, message, Table} from "antd"
import ManufacturerInfoType from '../../../types/ManufacturerInfo'
import {connect, ConnectedProps} from 'react-redux'
import {
    getAreaName,
    listManufacturer,
    listManufacturerOnID,
    queryManufacturerInfoAmount,
    queryManufacturerInfoAmountOnID,
    searchManufacturer
} from "../../../requests/Manufacturer";
import {devRes, getRes, prodRes} from "../../../configFile";
import {RootState} from "../../../reducers";
import UserType from '../../../types/UserType';
import Axios from 'axios';

interface PropsFromRedux extends ConnectedProps<typeof connector> { }
interface IState {
    ManufacturerSource: Array<ManufacturerInfoType & { key: number }>
    amount: number
    offset: number
    limit: number
    isSearch: boolean
}
const { Search } = Input;
class ManufacturerInfoList extends Component<PropsFromRedux, IState> {
    constructor(props: PropsFromRedux) {
        super(props)
        this.state = {
            ManufacturerSource: [],
            amount: 0,
            offset: 0,
            limit: 10,
            isSearch: false
        }
    }
    //获取厂商数据
    getManufacturer = async () => {
        try {
            const amountRes = this.props.userType === UserType.SUPERVISOR
                ?
                getRes(await queryManufacturerInfoAmount())
                :
                getRes(await queryManufacturerInfoAmountOnID(this.props.userID))
            const res = this.props.userType === UserType.SUPERVISOR
                ?
                getRes(await listManufacturer(this.state.offset, this.state.limit))
                :
                getRes(await listManufacturerOnID(this.state.offset, this.state.limit, this.props.userID))
            if (amountRes.isSuccessful && res.isSuccessful) {
                const areasRes: Array<devRes | prodRes> = (await Axios.all(res.data.map((itemManu: ManufacturerInfoType) =>
                    itemManu.manufacturerAddress.split(',')[0]).map((itemCode: string) => {
                    return getAreaName(itemCode)
                }))).map(item => getRes(item as devRes | prodRes).data)
                this.setState({
                    ManufacturerSource: res.data.map((item: ManufacturerInfoType, index: number) => Object.assign({}, item, {
                        manufacturerAddress: areasRes[index] + ' ' + (item.manufacturerAddress.split(',').slice(1).join(''))
                    }, { key: item.manufacturerID })),
                    amount: amountRes.data
                })
            } else {
                message.error("获取失败" + amountRes.message + '  ' + res.message)
                return;
            }

        }
        catch (error) {
            message.error(error.toString())
        }
    }

    componentDidMount() {
        this.getManufacturer()
    }

    columns = [{
        title: '厂商名称',
        dataIndex: 'manufacturerName',
        key: 'manufacturerName',
        width: 100
    },
        {
            title: '厂商地址',
            dataIndex: 'manufacturerAddress',
            key: 'manufacturerAddress',
            width: 150
        },
        {
            title: '联系方式',
            dataIndex: 'manufacturerTelephone',
            key: 'manufacturerTelephone',
            width: 100,
        },
        {
            title: '厂商简介',
            dataIndex: 'manufacturerIntroduction',
            key: 'manufacturerIntroduction',
            width: 250
        }]

    onSearch: (values: string) => void = async values => {
        if (values === '') {
            await this.getManufacturer()
        } else {
            try {
                const res = getRes(await searchManufacturer(values))
                if (res.isSuccessful) {
                    this.setState({ ManufacturerSource: res.data, amount: res.data.length, isSearch: true })
                } else {
                    console.error(res);
                    message.error("查询失败")
                }
            } catch (err) {
                message.error(JSON.stringify(err))
            }
        }
    }

    render() {
        return (
            <div>
                <Search placeholder="搜索" onSearch={values => this.onSearch(values)} allowClear={true} enterButton />
                <Table columns={this.columns}
                       dataSource={this.state.ManufacturerSource}
                       pagination={{
                           onChange: this.state.isSearch ? undefined : (page, pageSize) => {
                               console.log(page, pageSize);
                               if (!!pageSize) {
                                   this.setState({
                                       offset: (page - 1) * (pageSize),
                                       limit: (pageSize)
                                   },()=>{
                                       this.getManufacturer()
                                   })
                               } else {
                                   console.error('pageSize === undefinde')
                               }
                           },
                           defaultPageSize: this.state.limit,
                           total: this.state.amount,
                           showSizeChanger: false
                       }} />
            </div>
        )
    }
}

//connect加入props
const mapStateToProps = (state: RootState) => {
    return {
        userID: state.loginReducers.userID,
        userType: state.loginReducers.userType
    }
}

const connector = connect(mapStateToProps)

export default connector(ManufacturerInfoList)